package com.wiringweb.servlet;

import com.wiringweb.parameterprocessor.ParameterProcessorInterface;
import java.util.regex.Matcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Dmitry
 */
public class RequestParameterProcessor {
    public Object[] parameterProcessor(String url, UrlBind binding, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ParameterProcessorInterface[] processors = binding.getParameterProcessors();
        Object[] parameter = new Object[processors.length];
        Matcher matcher = binding.getMatcher().matcher(url);
        matcher.matches();
        String[] urlParams = new String[matcher.groupCount()];
        for (int i = 0; i < matcher.groupCount(); i++) {
            urlParams[i] = matcher.group(i + 1);
        }

        int paramIndex = 0;
        for (int i = 0; i < processors.length; i++) {
            ParameterProcessorInterface ppi = processors[i];
            Object value = ppi.process(response, request, urlParams, paramIndex);
            paramIndex += ppi.getProcessedGroupCount();
            parameter[i] = value;
        }

        return parameter;
    }
}
